package com.example.demo.web.manage.service;

import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.solon.annotation.Db;
import com.example.demo.web.manage.convert.UserConvert;
import com.example.demo.web.manage.dto.UserDeptDto;
import com.example.demo.web.manage.dto.UserDto;
import com.example.demo.web.manage.model.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.*;
import org.noear.solon.data.annotation.Tran;

/**
 * @author airhead
 */
@Component
@Slf4j
public class UserService {
  @Db("db1")
  private EasyEntityQuery entityQuery;

  @Inject private UserDeptService userDeptService;

  @Tran
  public void addAll(UserDto userDto) {
    UserEntity user = UserConvert.INSTANCE.convert(userDto);

    entityQuery.insertable(user).executeRows(true);

    UserDeptDto userDeptDto = new UserDeptDto();
    userDeptDto.setUserId(user.getId());
    userDeptDto.setDeptId(userDto.getDeptId());

    userDeptService.addUserDept(userDeptDto);
  }

  @Tran
  public void rollbackAll(UserDto userDto) {
    UserEntity user = UserConvert.INSTANCE.convert(userDto);

    entityQuery.insertable(user).executeRows(true);

    UserDeptDto userDeptDto = new UserDeptDto();
    userDeptDto.setUserId(user.getId());
    userDeptDto.setDeptId(userDto.getDeptId());
    userDeptService.rollbackUserDept(userDeptDto);
  }

  @Tran
  public Boolean rollbackAll1(UserDto userDto) {
    UserEntity user = UserConvert.INSTANCE.convert(userDto);

    entityQuery.insertable(user).executeRows(true);

    UserDeptDto userDeptDto = new UserDeptDto();
    userDeptDto.setUserId(user.getId());
    userDeptDto.setDeptId(userDto.getDeptId());
    userDeptService.addUserDept(userDeptDto);

    throw new RuntimeException("不能添加主表");
  }

  @Tran
  public void rollbackSub(UserDto userDto) {
    UserEntity user = UserConvert.INSTANCE.convert(userDto);

    entityQuery.insertable(user).executeRows(true);

    UserDeptDto userDeptDto = new UserDeptDto();
    userDeptDto.setUserId(user.getId());
    userDeptDto.setDeptId(userDto.getDeptId());

    try {
      userDeptService.rollbackUserDept1(userDeptDto);
    } catch (Exception ignore) {
      // 忽略子表的异常
    }
  }

  @Tran
  public void rollbackMaster(UserDto userDto) {
    UserEntity user = UserConvert.INSTANCE.convert(userDto);

    entityQuery.insertable(user).executeRows(true);

    UserDeptDto userDeptDto = new UserDeptDto();
    userDeptDto.setUserId(user.getId());
    userDeptDto.setDeptId(userDto.getDeptId());

    userDeptService.addUserDept1(userDeptDto);

    throw new RuntimeException("不能添加主表");
  }
}
